<template>
	<view class="music-view">
		<view class="music-container">
			<view id="dmplayer" :prop="option" :change:prop="dplayer.update"></view>
		</view>
	</view>
</template>

<script>
import musicSer from '@/api/service/music.js'

export default {
	data() {
		return {
      option: {
        music: null,
        musics: []
      },
			list: []
		}
	},

	onNavigationBarButtonTap(arg) {
		// 上传
		if (arg.category === 'manager') {
			this.handleManager()
		}
	},

	mounted() {
    this.initSources()
	},

	methods: {
    // 初始化资源
    initSources () {
      return musicSer.queryListAll().then(data => {
        let playlist = Array.isArray(data) ? data : []
        // 按歌手排序
        let list = playlist.sort((a, b) => {
          return String(a.singer || '').localeCompare(String(b.singer || ''))
        })
        this.option.musics = list
      })
    },
		// 音乐管理
		handleManager () {
      uni.navigateTo({
        url: '/pages/music/manager'
      })
		}
	}
}
</script>

<script module="dplayer" lang="renderjs">
import '@daelui/dmplayer/dist/style/dmplayer.css'
import DMPlayer from '@daelui/dmplayer'

export default {
	data() {
		return {
      sources: []
    }
	},

	mounted() {
		// 初始化播放器
		this.initAudio()
	},

	methods: {
    update (newValue) {
      if (!this.player || this.updated) {
        return true
      }
      this.player.ready(() => {
        if (newValue.musics && newValue.musics.length) {
          this.sources = newValue.musics
          this.player.addSources(newValue.musics)
          this.updated = true
        }
        if (newValue.music && newValue.music.url) {
          this.player.changeAudioByData(newValue.music)
          setTimeout(() => {
            this.player.play()
          }, 100)
        } else if (this.sources[0]) {
          this.player.changeAudioByIndex(0)
        }
      })
    },
		// 初始化播放器
    initAudio() {
      this.player = new DMPlayer('#dmplayer', {
        sources: this.sources,
        scene: 'standard',
        isFromStore: true
      })
		}
	}
}
</script>

<style lang="less" scoped>
.music-view {
	position: absolute;
	top: 0;
	bottom: 0;
	left: 0;
	right: 0;
	overflow: hidden;
	.music-container {
		overflow: auto;
		position: relative;
		height: 100%;
    -webkit-overflow-scrolling: touch;
    &::-webkit-scrollbar {
      display: none; // 隐藏滚动条
    }
	}
}
</style>
